﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DienThoai;

namespace DienThoai.MODELS
{
    public class LoginModel
    {
        public delegate void LoginEventHandler(object sender, LoginEventArgs e);
        public event LoginEventHandler LoginEvent;
        
        private DienThoaiDataContext db = new DienThoaiDataContext();

        private static LoginModel instance;

        private LoginModel() { }

        public static LoginModel Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new LoginModel();
                }
                return instance;
            }
        }

        public void Authenticate(string userName, string passWord)
        {
            try
            {
                var t = (from role in db.Staffs
                         where role.Username == userName && role.Password == passWord
                         select role.RoleID).Single();
                foreach (var item in t)
                {
                    //Store keeper
                    if (item == '3')
                    {
                        OnLoginCompleted(new LoginEventArgs(Consts.AccountType.StoreKeeper, userName, passWord));
                    }
                    //Admin
                    if (item == '1')
                    {
                        OnLoginCompleted(new LoginEventArgs(Consts.AccountType.Admin,userName,passWord));
                    }
                    //Staff
                    if (item == '2')
                    {
                        OnLoginCompleted(new LoginEventArgs(Consts.AccountType.Staff, userName, passWord));
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        private void OnLoginCompleted(LoginEventArgs e)
        {
            if (LoginEvent != null)
            {
                LoginEvent(this, e);
            }
        }
    }

    public class LoginEventArgs : EventArgs
    {
        private Consts.AccountType type;

        private string userName;

        private string passWord;

        public LoginEventArgs() { }

        public LoginEventArgs(Consts.AccountType tmp, string userName, string passWord)
        {
            type = tmp;
            this.userName = userName;
            this.passWord = passWord;
        }

        public Consts.AccountType Type
        {
            get { return type; }
            set { type = value; }
        }

        public string UserName
        {
            get { return userName; }
            set { userName = value; }
        }

        public string PassWord
        {
            get { return passWord; }
            set { passWord = value; }
        }
    }
}
